package com.yuhang.apiTest.state;/**
 * Copyright (c) 2018-2028 尚硅谷 All Rights Reserved
 * <p>
 * Project: FlinkTutorial
 * Package: com.atguigu.apitest.state
 * Version: 1.0
 * <p>
 * Created by wushengran on 2020/11/10 16:33
 */

import com.yuhang.bean.SensorReading;
import com.yuhang.wordcount.WordCount;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.ListState;
import org.apache.flink.api.common.state.ListStateDescriptor;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.tuple.Tuple3;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * @ClassName: StateTest3_KeyedStateApplicationCase
 * @Description:
 * @Author: wushengran on 2020/11/10 16:33
 * @Version: 1.0
 */
public class KeyedStateCase {
    public static void main(String[] args) throws Exception{

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        DataStreamSource<String> inputStream = env.socketTextStream("hadoop100", 7777);

        SingleOutputStreamOperator<SensorReading> dataStream = inputStream.map(data -> {
            String[] split = data.split(",");
            return new SensorReading(split[0], new Long(split[1]), new Double(split[2]));
        });

        SingleOutputStreamOperator<Tuple3<String,Double,Double>> resultStream = dataStream.keyBy("id")
                .flatMap(new TempChangeWarning(10.0));


    }

    public static class TempChangeWarning extends RichFlatMapFunction<SensorReading,Tuple3<String,Double,Double>>{
        // 私有属性，温度跳变阈值
        private Double threshold;

        // 定义状态，保存上一次的温度值
        private ValueState<Double> tempListState;

        public TempChangeWarning(Double threshold) {
            this.threshold = threshold;
        }

        @Override
        public void open(Configuration parameters) throws Exception {
            tempListState = getRuntimeContext().getState(new ValueStateDescriptor<Double>("last-temp",Double.class));

        }

        @Override
        public void flatMap(SensorReading value, Collector<Tuple3<String, Double, Double>> out) throws Exception {
            // 获取状态
            Double lastTemp = tempListState.value();

            // 如果状态不为null，那么就判断两次温度差值
            if (tempListState != null){
                Double diff = Math.abs( value.getTemperature() - lastTemp );

                if( diff >= threshold )
                    out.collect(new Tuple3<>(value.getId(), lastTemp, value.getTemperature()));
            }
            // 更新状态
            tempListState.update(value.getTemperature());
        }

        @Override
        public void close() throws Exception {
            tempListState.clear();
        }
    }

}
